package com.netty.client;

import com.alibaba.fastjson.JSON;
import com.netty.model.UserDto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("服务端信息:{}", ctx.channel().remoteAddress());
        log.info("客户端接收服务端信息: {}", msg);
    }

    //当连接建立好的使用调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // ctx.channel().writeAndFlush("你好，服务端！");
        // 模拟用户注册
        UserDto loginDto = new UserDto();
        loginDto.setName("netty");
        loginDto.setType("1");
        String jsonString = JSON.toJSONString(loginDto);
        // 发送到服务端
        ctx.writeAndFlush(jsonString);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
